<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Shopify App</title>
    <script src="https://unpkg.com/@shopify/app-bridge@3"></script>
    <style>
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            margin: 0;
            padding: 20px;
            background-color: #f6f6f7;
        }
        .container {
            max-width: 800px;
            margin: 0 auto;
            background: white;
            padding: 40px;
            border-radius: 8px;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
        }
        h1 {
            color: #202223;
            margin-bottom: 20px;
        }
        .status {
            padding: 16px;
            background: #f0f8f0;
            border: 1px solid #9fd89f;
            border-radius: 4px;
            margin: 20px 0;
        }
        .button {
            background: #008060;
            color: white;
            border: none;
            padding: 12px 24px;
            border-radius: 4px;
            cursor: pointer;
            margin: 10px 5px 10px 0;
        }
        .button:hover {
            background: #007552;
        }
        .products-count {
            font-size: 24px;
            font-weight: bold;
            color: #008060;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>🛍️ Shopify 应用仪表板</h1>
        
        <div class="status">
            <strong>✅ 应用状态:</strong> 已连接到商店
        </div>
        
        <div>
            <h2>📊 商店统计</h2>
            <p>商店产品总数: <span id="product-count" class="products-count">加载中...</span></p>
            <button class="button" onclick="getProductCount()">刷新产品数量</button>
        </div>
        
        <div>
            <h2>🛠️ 快速操作</h2>
            <button class="button" onclick="createProduct()">创建示例产品</button>
            <button class="button" onclick="getAuthInfo()">获取授权信息</button>
            <button class="button" onclick="copyAccessToken()">复制访问令牌</button>
        </div>
        
        <div id="auth-info" style="display: none;">
            <h2>🔑 授权信息</h2>
            <div style="background: #f6f6f7; padding: 15px; border-radius: 4px; margin: 10px 0;">
                <h3>访问令牌</h3>
                <code id="access-token" style="word-break: break-all; background: white; padding: 10px; display: block; border-radius: 4px;"></code>
                <button class="button" onclick="copyToClipboard('access-token')" style="margin-top: 10px;">复制令牌</button>
            </div>
            
            <div style="background: #f6f6f7; padding: 15px; border-radius: 4px; margin: 10px 0;">
                <h3>cURL 示例</h3>
                <pre id="curl-examples" style="background: white; padding: 10px; border-radius: 4px; overflow-x: auto; font-size: 12px;"></pre>
                <button class="button" onclick="copyToClipboard('curl-examples')" style="margin-top: 10px;">复制 cURL</button>
            </div>
            
            <div style="background: #f6f6f7; padding: 15px; border-radius: 4px; margin: 10px 0;">
                <h3>完整授权数据 (JSON)</h3>
                <pre id="full-auth-data" style="background: white; padding: 10px; border-radius: 4px; overflow-x: auto; font-size: 12px; max-height: 400px; overflow-y: auto;"></pre>
                <button class="button" onclick="copyToClipboard('full-auth-data')" style="margin-top: 10px;">复制 JSON</button>
            </div>
        </div>
        
        <div id="message"></div>
    </div>

    <script>
        // 初始化 Shopify App Bridge
        let app = null;
        let authenticatedFetch = null;
        
        function initializeShopifyApp() {
            const config = window.shopifyConfig || {};
            const apiKey = config.apiKey || '%VITE_SHOPIFY_API_KEY%';
            const host = config.host || new URLSearchParams(window.location.search).get('host');
            
            if (apiKey && apiKey !== '%VITE_SHOPIFY_API_KEY%' && host) {
                try {
                    // 创建App Bridge应用实例
                    app = window['app-bridge'].createApp({
                        apiKey: apiKey,
                        host: host
                    });
                    
                    // 获取authenticatedFetch用于API调用
                    authenticatedFetch = window['app-bridge'].authenticatedFetch(app);
                    
                    console.log('✅ Shopify App Bridge 已初始化');
                    console.log('- API Key:', apiKey);
                    console.log('- Host:', host);
                    console.log('- Shop:', config.shop);
                    
                    return true;
                } catch (error) {
                    console.error('❌ Shopify App Bridge 初始化失败:', error);
                    return false;
                }
            } else {
                console.warn('⚠️ 缺少必要参数，无法初始化Shopify App Bridge');
                console.log('- API Key:', apiKey);
                console.log('- Host:', host);
                return false;
            }
        }
        
        // 页面加载时初始化
        document.addEventListener('DOMContentLoaded', function() {
            initializeShopifyApp();
        });
        
        // 获取产品数量
        async function getProductCount() {
            try {
                console.log('🔍 获取产品数量...');
                let response;
                
                if (authenticatedFetch) {
                    // 使用Shopify的authenticatedFetch
                    response = await authenticatedFetch('/api/products/count');
                } else {
                    // 回退到普通fetch
                    response = await fetch('/api/products/count');
                }
                
                const data = await response.json();
                document.getElementById('product-count').textContent = data.count || 0;
                console.log('✅ 产品数量获取成功:', data.count);
            } catch (error) {
                console.error('❌ 获取产品数量失败:', error);
                document.getElementById('product-count').textContent = '获取失败';
            }
        }
        
        // 创建示例产品
        async function createProduct() {
            const messageDiv = document.getElementById('message');
            messageDiv.innerHTML = '<p style="color: #008060;">正在创建产品...</p>';
            
            try {
                console.log('🔍 创建示例产品...');
                let response;
                
                if (authenticatedFetch) {
                    // 使用Shopify的authenticatedFetch
                    response = await authenticatedFetch('/api/products', { method: 'POST' });
                } else {
                    // 回退到普通fetch
                    response = await fetch('/api/products', { method: 'POST' });
                }
                
                const data = await response.json();
                
                if (data.success) {
                    messageDiv.innerHTML = '<p style="color: #008060;">✅ 示例产品创建成功！</p>';
                    console.log('✅ 产品创建成功');
                    getProductCount(); // 刷新产品数量
                } else {
                    messageDiv.innerHTML = `<p style="color: #d72c0d;">❌ 创建失败: ${data.error}</p>`;
                    console.error('❌ 产品创建失败:', data.error);
                }
            } catch (error) {
                console.error('❌ 创建产品时发生错误:', error);
                messageDiv.innerHTML = '<p style="color: #d72c0d;">❌ 创建产品时发生错误</p>';
            }
        }
        
        // 获取授权信息
        async function getAuthInfo() {
            try {
                console.log('🔍 获取授权信息...');
                let response;
                
                if (authenticatedFetch) {
                    response = await authenticatedFetch('/api/auth/info');
                } else {
                    response = await fetch('/api/auth/info');
                }
                
                const authData = await response.json();
                
                if (response.ok) {
                    console.log('✅ 授权信息获取成功');
                    
                    // 显示授权信息区域
                    document.getElementById('auth-info').style.display = 'block';
                    
                    // 填充访问令牌
                    document.getElementById('access-token').textContent = authData.accessToken;
                    
                    // 填充cURL示例
                    const curlText = `# 获取产品列表
${authData.curlExamples.getProducts}

# GraphQL查询
${authData.curlExamples.graphqlQuery}

# 创建产品
${authData.curlExamples.createProduct}`;
                    document.getElementById('curl-examples').textContent = curlText;
                    
                    // 填充完整JSON数据
                    document.getElementById('full-auth-data').textContent = JSON.stringify(authData, null, 2);
                    
                    // 滚动到授权信息区域
                    document.getElementById('auth-info').scrollIntoView({ behavior: 'smooth' });
                    
                } else {
                    console.error('❌ 获取授权信息失败:', authData);
                    alert('获取授权信息失败: ' + authData.message);
                }
                
            } catch (error) {
                console.error('❌ 获取授权信息时发生错误:', error);
                alert('获取授权信息时发生错误');
            }
        }
        
        // 快速复制访问令牌
        async function copyAccessToken() {
            try {
                let response;
                
                if (authenticatedFetch) {
                    response = await authenticatedFetch('/api/auth/info');
                } else {
                    response = await fetch('/api/auth/info');
                }
                
                const authData = await response.json();
                
                if (response.ok && authData.accessToken) {
                    await navigator.clipboard.writeText(authData.accessToken);
                    alert('✅ 访问令牌已复制到剪贴板！');
                } else {
                    alert('❌ 无法获取访问令牌');
                }
                
            } catch (error) {
                console.error('❌ 复制访问令牌失败:', error);
                alert('❌ 复制失败');
            }
        }
        
        // 复制到剪贴板
        async function copyToClipboard(elementId) {
            try {
                const element = document.getElementById(elementId);
                const text = element.textContent;
                await navigator.clipboard.writeText(text);
                alert('✅ 已复制到剪贴板！');
            } catch (error) {
                console.error('❌ 复制失败:', error);
                alert('❌ 复制失败');
            }
        }
        
        // 页面加载时获取产品数量
        document.addEventListener('DOMContentLoaded', function() {
            // 延迟执行，确保Shopify App Bridge已初始化
            setTimeout(() => {
                getProductCount();
            }, 1000);
        });
    </script>
</body>
</html>
